<template>
    <div>
        <div class="container">
            <div class="left">
                <div class="search-blog">
                    <el-input v-model="search" size="small" placeholder="输入标题" class="search-input"/>
                </div>
                <div v-for="item in filterTableData" :key="item.id">
                    <BlogItem
                            :title="item.title"
                            :cover="item.cover"
                            :summary="item.description"
                            :writer="item.writer"
                            :categoryName="item.categoryName"
                            :time="item.time"
                            :blogId="item.blogId"
                            :categoryId="item.categoryId"
                            :isLike="item.isLike"
                            :likes="item.likes"
                            @likes="updateLikes"
                    ></BlogItem>
                </div>
            </div>
            <div class="right">
                <div class="part-title">
                    <span class="title">分类专栏</span>
                    <router-link to="/" class="a-link">更多&gt;&gt;</router-link>
                </div>
                <div v-for="item in categoryList" :key="item.id">
                    <CategoryItem :cover="item.cover" :name="item.categoryName" :blogCount="item.blogCount"
                                  :categoryId="item.categoryId"></CategoryItem>
                </div>

<!--                <div>-->
<!--                    <span>曝光卷</span>-->
<!--                </div>-->
                <!-- 修改此处的 ID 为 mainBar -->

                <div id="mainBar" style="width: 330px; height: 200px;"></div>
                <div id="mainGlobe" style="width: 300px; height: 200px;"></div>
            </div>
        </div>
        <!-- 新增小地球的部分 -->
        <div class="container">
            <div class="left">
                <!-- 略去不相关部分 -->
            </div>
            <div class="right">
                <div class="part-title">
                    <!-- 略去不相关部分 -->
                </div>
                <!-- 修改此处的 ID 为 mainGlobe -->

            </div>
        </div>
    </div>
</template>

<script setup>
    import {onMounted} from 'vue';
    import * as echarts from 'echarts/core';
    import {GridComponent, LegendComponent} from 'echarts/components';
    import {BarChart} from 'echarts/charts';
    import {CanvasRenderer} from 'echarts/renderers';
    import {ref, computed} from 'vue';
    import axios from 'axios';
    import 'echarts-gl';

    const blogList = ref([]);
    const search = ref('');
    const jwtToken = localStorage.getItem('jwtToken');
    // 解码JWT令牌（假设它是一个包含用户名的 JSON）
    const tokenData = JSON.parse(decodeURIComponent(escape(atob(jwtToken.split('.')[1]))));
    console.log('Token Data:', tokenData.token);
    localStorage.setItem('tokenValue', tokenData.token.tokenValue);
    // 设置用户名
    const axiosInstance = axios.create({
        headers: {
            'Token': jwtToken,
            'satoken':localStorage.getItem('tokenValue')
        }
    });
    // 监听子组件触发的 likes 事件，并更新相关数据
    const updateLikes = ({ isLike, likes}) => {
        // 假设 item 是一个响应式对象
        item.isLike = isLike;
        item.likes = likes;
    };
    axios.get('http://127.0.0.1:8080/showblog')
        .then(response => {
            const responseData = response.data;
            if (Array.isArray(responseData.data) && responseData.data.length > 0) {
                blogList.value = responseData.data;
            }
        })
        .catch(error => {
            /* window.location.href = 'http://localhost:8080/login'; */
            console.log(66666666666666666666)
            console.error('请求失败:', error);
        });

    const categoryList = ref([]);
    axiosInstance.get('http://127.0.0.1:8080/show')
        .then(response => {
            const responseData = response.data;
            if (Array.isArray(responseData.data) && responseData.data.length > 0) {
                categoryList.value = responseData.data;
            }
        })
        .catch(error => {
            console.error('请求失败:', error);
        });

    const filterTableData = computed(() =>
        blogList.value.filter(data =>
            !search.value ||
            data.title.toLowerCase().includes(search.value.toLowerCase())
        )
    );

    echarts.use([GridComponent, LegendComponent, BarChart, CanvasRenderer]);

    async function fetchBlogData() {
        try {
            const response = await axiosInstance.get('http://127.0.0.1:8080/showblog');
            blogList.value = response.data.data;
            blogList.value.sort((a, b) => b.browse - a.browse);
        } catch (error) {
            console.error('请求失败:', error);
        }
    }

    const barOption = {
        yAxis: {
            type: 'category',
            data: [],
            inverse: true,
            animationDuration: 300,
            animationDurationUpdate: 300,
        },
        xAxis: {
            type: 'value',
            max: 10,
        },
        series: [
            {
                realtimeSort: true,
                name: '博客浏览记录',
                type: 'bar',
                data: [],
                label: {
                    show: true,
                    position: 'right',
                    valueAnimation: true,
                },
            },
        ],
        legend: {
            show: true,
        },
        animationDuration: 0,
        animationDurationUpdate: 3000,
        animationEasing: 'linear',
        animationEasingUpdate: 'linear',
    };

    let barChart;

    function initBarChart() {
        // 修改此处的 ID 为 mainBar
        barChart = echarts.init(document.getElementById('mainBar'));
        barChart.setOption(barOption);
    }

    function runBarChart() {
        const topThreeBlogs = blogList.value.slice(0, 3);
        const newData = topThreeBlogs.map(item => item.browse);
        const newYAxisData = topThreeBlogs.map(item => item.title);

        const animationDuration = 3000;

        barChart.setOption({
            series: [
                {
                    type: 'bar',
                    data: newData,
                    animation: true,
                    animationEasing: 'linear',
                    animationDuration: animationDuration,
                },
            ],
            yAxis: {
                data: newYAxisData,
                inverse: true,
            },
            xAxis: {
                type: 'value',
                max: Math.max(...newData) + 10,
                min: 0,
            },
        });
    }

    onMounted(async () => {
        await fetchBlogData();
        initBarChart();
        runBarChart();
        setInterval(runBarChart, 3000);
    });

    // 小地球的部分
    const globeOption = {
        backgroundColor: null,
        globe: {
            baseTexture: './src/assets/world.topo.bathy.200401.jpg',
            heightTexture: './src/assets/world.topo.bathy.200401.jpg',
            displacementScale: 0.04,
            shading: 'realistic',
            /*  environment: 'src/assets/starfield.jpg', */
            environment: null,
            realisticMaterial: {
                roughness: 0.9
            },
            postEffect: {
                enable: true
            },
            light: {
                main2: {
                    intensity: 5,
                    shadow: true
                },
                ambientCubemap: {
                    texture: 'src/assets/pisa.hdr',
                    diffuseIntensity: 0.2
                }
            }
        }
    };

    let globeChart;

    function initGlobeChart() {
        // 修改此处的 ID 为 mainGlobe
        globeChart = echarts.init(document.getElementById('mainGlobe'));
        globeChart.setOption(globeOption);
    }

    onMounted(async () => {
        initGlobeChart();
    });

</script>

<style lang="scss">
    .container {
        display: flex;
        margin-top: 10px;

        .left {
            .search-blog {
                width: 20%;
                border: 2px;
                float: right;
            }

            flex: 1;
            background: #fff;
            padding: 15px;
        }

        .right {
            margin-left: 10px;
            width: 300px;
            background: #fff;

            .part-title {
                display: flex;
                align-items: center;
                justify-content: space-between;
                border-bottom: 1px solid #ddd;
                padding: 0px 5px 8px 5px;
                text-decoration: none;
            }
        }
    }
</style>